#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time     : 2018/8/21 10:38
# @Author   : crabtesting@163.com
# @File     : bugEmail.py
# -*- coding: utf-8 -*-

import jira
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def sendBugEmail(Url,UserName,Password,ProjectArr,bugStatus,bugurl):
    jac = jira.JIRA(Url,basic_auth=(UserName,Password)) # 登录JIRA
    Allstatus = jac.statuses() # 获取所有的status任务状态，如：打开、进行中、待验证、关闭...
    bugStatusId = []
    for status in Allstatus:
        if status.name in bugStatus:
            bugStatusId.append(status.id)
    bugStatusId = str(bugStatusId)[1:-1]
    ProjectArr = str(ProjectArr)[1:-1]
    issue = jac.search_issues(jql_str="project IN (%s) AND type = Bug AND status IN (%s)"%(ProjectArr,bugStatusId)) # 通过执行JQL进行查询，关于JQL，可以百度上查找相关资料
    bugNum = len(issue)
    if bugNum >= 1:
        allissue = {}
        allassigneeName = []
        receivers = []
        for issueName in issue:
            alldict = jac.issue(issueName).fields.__dict__   # 因jira系统的差别，下面的字段可能会有差别，具体可以通过打印当前的这个值来查看详情
            assigneeName = alldict['assignee'].displayName #等价于 jac.issue(issueName).fields.assignee # 取到的是jira单当前的经办人
            assigneeEmail = alldict['assignee'].emailAddress # 取到的是jira单当前的经办人的邮箱
            if assigneeEmail not in receivers:
                receivers.append(assigneeEmail)
                allassigneeName.append(assigneeName)
                allissue[assigneeEmail] = [assigneeName]
            allissue[assigneeEmail].append("%s%s"%(bugurl,issueName))

        messageText = []
        for j,issueValues in  allissue.items():
            messageText.append("\n    ".join(issueValues))
        messageText = "\n\n".join(messageText)

        sender = 'crabtesting@163.com'
        receivers=receivers+['crabtesting1@163.com','crabtesting2@163.com']
        allassigneeName=allassigneeName+["crabtesting1","crabtesting2"]
        receivers = set(receivers) # 去重
        allassigneeName = "; ".join(set(allassigneeName))
        # 下面开始发送邮件，详细用法，请阅读“菜鸟教程”中的smtplib
        try:
            smtpObj = smtplib.SMTP('localhost')
            message = MIMEText(messageText, 'plain', 'utf-8') # 邮件内容指定文本形式
            message['From'] = Header("Crab <crabtesting@163.com>", 'utf-8')
            message['To'] =  Header(allassigneeName, 'utf-8')
            message['Subject'] = Header("还有%s个BUG，请相关人员及时解决"%(bugNum), 'utf-8')
            smtpObj.sendmail(sender, receivers, message.as_string())
            print("邮件发送成功")
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")

if __name__ == '__main__':
    Url = "http://jira.crabtesting.com" #jira地址
    UserName = "crab"  #用户名
    Password = "crabPassword"  #用户密码
    ProjectArr = ["运营技术-交易团队"]  # jira中对应的项目组project
    bugStatus = ["开始","进行中","重新打开"]  # 要查找的处于哪些状态的bug
    bugurl = "http://jira.crabtesting.com/browse/" # 问题单的地址前缀，如：http://jira.crabtesting.com/browse/POSRT-2018，其中POSRT-2018为jira单号，取前面通用的地址
    sendBugEmail(Url,UserName,Password,ProjectArr,bugStatus,bugurl)